package org.geektimes.configuration.microprofile.config.source;

import org.eclipse.microprofile.config.spi.ConfigSource;
import org.geektimes.configuration.microprofile.config.constant.ConfigConstant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceConfigurationError;
import java.util.Set;
import java.util.logging.Logger;

public class ExternalFileConfigSource implements ConfigSource {

    private static final String PREFIX = "META-INF/";

    private static final String FILE_NAME = "microprofile-config.properties";

    private Logger logger = Logger.getLogger(this.getName());

    private Map<String, String> properties;

    public ExternalFileConfigSource() {
        String filepath = PREFIX + FILE_NAME;
        try {
            InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filepath);
            properties = new HashMap<>();
            // 此处不考虑同名文件的config_ordinal属性问题了
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
            String line;
            while ((line=reader.readLine()) != null) {
                line = line.trim();
                if (line.indexOf("=") == -1)
                    throw new ServiceConfigurationError("Illegal configuration-file syntax");

                String[] characters = line.split("=");
                String value = characters.length == 2?characters[1]:"";
                properties.put(characters[0], value);
            }


        } catch (IOException e) {
            logger.severe("Error locating configuration files: " + e.getMessage());
        }
    }

    @Override
    public Set<String> getPropertyNames() {
        return Collections.unmodifiableSet(this.properties.keySet());
    }

    @Override
    public Map<String, String> getProperties() {
        return Collections.unmodifiableMap(this.properties);
    }

    @Override
    public String getValue(String propertyName) {
        return this.properties.get(propertyName);
    }

    @Override
    public String getName() {
        return "Configuration File Properties";
    }

    @Override
    public int getOrdinal() {
        return ConfigConstant.EXT_FILE_ORDINAL;
    }
}
